<?php
/**
 * 服务器管理
 * User: leishaofa
 * Date: 2017/8/07
 * Time: 10:50
 */
#use Ecs\Request\V20140526\DescribeInstancesRequest;

class ServiceAction extends CommonAction{
    /**
     *@auth:leishaofa
     *@date:20170807
     * @efect:服务器平台配置
     */
    public function serviceConf(){
        if(IS_POST) {
            $config_file = CONF_PATH .'service.php';
            $data=$_POST['ServerProvider'];
            $newconfig['ServerProvider']=array_map(function($val) use ($data){
                $val['is_display']=isset($data[$val['val']])?filter_var($data[$val['val']],FILTER_VALIDATE_BOOLEAN):false;
                return $val;
            },C('ServerProvider'));
            $this->update_config($newconfig, $config_file);
            $this->ajaxSuccess('设置成功');
            exit;
        }
        C('TOKEN_ON',false);
        $this->display();
    }

    /**
     * @auth:leishaofa
     * @date:20170919
     * @efect:获取区域
     */
    public function regions(){
        $memberinfo=session('member_info');
        if(IS_AJAX && IS_POST) {
            $sername = htmlspecialchars($_POST['keyid']);
            $zone=trim($_POST['regionsid']);
            $model=M('','',C('flashSale'));
            $where= "where t_id = '".$memberinfo['t_id']."' ";
            $sql="select ser_id,ser_url,ser_key,ser_secret from f_service ".$where." and ser_type = ".$sername." ";
            $resultService=$model->query($sql);
            if(!$resultService){
                $this->ajaxError("请先添写该服务平台信息");
            }
            $data=$resultService[0];
            $data['Region']=$zone;
            switch ($sername){
                case 1:
                    $actiondata = array('Action' => 'DescribeAvailabilityZones');

                    $result=$this->meituanyun($data,$actiondata)['DescribeAvailabilityZonesResponse']['AvailabilityZoneSet']['AvailabilityZone'];
                    $region=array_filter($result,function($val){
                        return $val['Status'] == 'enable'?true:false;
                    });
                    break;
                case 2:
                    $data['model']='cvm';
                    $actiondata=array('Version'=>'2017-07-17');
                    $resultdata=$this->tencat($data,"DescribeZones",$actiondata);
                    if(isset($resultdata['Response']['TotalCount']) && $resultdata['Response']['TotalCount']>0){
                        $region=array_values(array_filter(array_map(function ($val){
                            if($val['ZoneState'] == 'AVAILABLE') {
                                $cache['Status'] = '';
                                $cache['availabilityZoneId'] = $val['ZoneId'];
                                $cache['availabilityZoneName'] = $val['Zone'];
                                $cache['availabilityZoneName_CN'] = $val['ZoneName'];
                                return $cache;
                            }else{
                                return false;
                            }
                        },$resultdata['Response']['ZoneSet'])));
                    }
                    break;
                case 4:
                    $actiondata=array('setRegionId'=>$zone);
                    $resultdata = json_decode(json_encode($this->ali($data, '\Ecs\Request\V20140526\DescribeZonesRequest', $actiondata)),true);//获取组
                    if(isset($resultdata['Zones']['Zone'])){
                        $region=array_values(array_filter(array_map(function ($val){
                            if(!empty($val['AvailableInstanceTypes']['InstanceTypes']) && count($val['AvailableInstanceTypes']['InstanceTypes'])>0) {
                                $cache['Status'] = '';
                                $cache['availabilityZoneId'] = $val['ZoneId'];
                                $cache['availabilityZoneName'] = $val['ZoneId'];
                                $cache['availabilityZoneName_CN'] = $val['LocalName'];
                                return $cache;
                            }else{
                                return false;
                            }
                        },$resultdata['Zones']['Zone'])));
                    }
                    break;
            }
            if($region){
                $this->ajaxSuccess("成功",$region);
            }else{
                $this->ajaxError("失败",[]);
            }
        }
    }



    /**
     * @auth:leishaofa
     * @date:20417804
     * @efect:新增平台套餐页面跳转和新增数据读取
     */
    public function platfromPakeageadd(){
        if(IS_AJAX){
            $id=is_numeric($_GET['keyid'])>0?$_GET['keyid']:'';//表自增id
            $siteModel = M('package_price','f_',C('flashSale'));
            if(IS_POST) {
                if (!$siteModel->autoCheckToken($_POST)){
                    $this->ajaxError('表单已提交过！请关闭重新填写！'); // 令牌验证错误
                }
                $data = $_POST;
                unset($data['__hash__']);
                if(!empty($_GET['keyid']) && empty($id)){//传了id但是id不是数字
                    $this->ajaxError("修改失败");
                }
                if(!empty($id)){
                    //修改
                    $status=filter_var($_POST['status'],FILTER_VALIDATE_BOOLEAN)?1:2;
                    $sql="INSERT INTO f_package_price(id,status) VALUES (".$id.",".$status.")ON DUPLICATE KEY UPDATE status=VALUES(status)";
                    $resultsql=$siteModel->execute($sql);
                    $msg=$resultsql>0?"修改成功":"修改失败";
                }else {
                    $issitedata=array_filter(C('ServerProvider'),function ($val) use($data){
                        $a=false;
                        if($val['val'] == $data['serverid']){
                            $a= $val['is_display'] == 1?true:false;
                        }
                        return $a;
                    });
                    $name=array_keys($issitedata)[0];
                    $issitedata=array_values($issitedata);
                    if (!$issitedata[0]['is_display']) {
                        $this->ajaxError("主机商错误");
                    }
                    if (empty($data['hostsdk'])) {
                        $this->ajaxError("请选择cpu和内存");
                    }
                    unset($data['serverid']);
                    $issetsql="select id from f_package_price where ser_type=".$issitedata[0]['val']."  and package_remark like '%hostsdk\":\"".$data['hostsdk']."\"%' and package_remark like '%sdktype\":\"".$data['sdktype']."\"%' and package_remark like '%zone\":\"".$data['zone']."\"}'  limit 1" ;
                    $insetresult= $siteModel->query($issetsql);
                    if(empty($insetresult)) {
                        $sql = "insert IGNORE into f_package_price(ser_type,ser_name,package_remark) values(" . $issitedata[0]['val'] . ",'" . $name. "','" . json_encode($data, JSON_UNESCAPED_UNICODE) . "')";
                        $resultsql = $siteModel->execute($sql);
                        $msg = $resultsql > 0 ? "添加成功" : "添加失败";
                    }else{
                        $resultsql=0;
                        $msg="该配置已经添加";
                    }
                }
                if ($resultsql > 0) {
                    parent::ajaxSuccess($msg);
                } else {
                    parent::ajaxError($msg);
                }
            }
            //查询修改信息
            if(!empty($id) && empty($_POST)){
                $sql="select * from f_package_price where id=".$id." ";
                $resultdata=$siteModel->query($sql);
                $resultdata[0]['package_remark']=json_decode( $resultdata[0]['package_remark'],true);
                if($resultdata){
                    $resultdata[0]['sercity']=getservercity($resultdata[0]['package_remark']['zone'],$resultdata[0]['ser_type']);
                    $this->assign('date',$resultdata[0]);
                }
                $this->display('platfromPakeageupdate');
                exit;
            }
            $this->display();
        }
    }

    /**
     *@auth:leishaofa
     *@date:20178022
     * @efect:获取主机配置信息
     */
    public function platfromDescribeInstanceTypes(){
        if(IS_AJAX){
            $siteid=htmlspecialchars($_POST['keyid']);
            $servertype=array_filter(array_map(function($val){ return empty($val['is_display'])?'':$val['val'];},C('ServerProvider')));
            $is_siteid =  array_search($siteid,$servertype);
            if (empty($is_siteid)) {
                $this->ajaxError("服务商不存在或者关闭");
            }
            $Model = M('','',C('flashSale'));
            $findservicesql = "select * from f_service where ser_type = " . $siteid." and is_member = 1";
            $resultoneService = $Model->query($findservicesql)[0];
            if(empty($resultoneService)){
                $this->ajaxError("服务商配置没有填写或者已经关闭");
            }

            $resultdata=[];
            $sdk=[];
            $resultoneService['Region']=$_POST['regionsid'];
            $zoneid=$_POST['zoneid'];
            switch ($resultoneService['ser_type']){
                case 1:
                    $actiondata=array('Action'=>'DescribeInstanceTypes','InstanceType'=>'Rabbitmq');
                    $result=$this->meituanyun($resultoneService,$actiondata)['DescribeInstanceTypesResponse']['InstanceTypeSet']['InstanceType'];
                    $resultdata['ECS']=[];
                    $Memory=[1,2,4,6,8,12,16,24,32];
                    $reg='/^C[0-9]{0,2}_M[0-9]{0,2}$/';
                    $result=array_filter($result,function($val) use ($reg){
                        return preg_match($reg,$val['instanceType'])?true:false;
                    });
                    foreach ($result as $key=>$val){
                        $val['memory'] = bcdiv($val['memory'], '1024', '0');
                        $val=array_change_key_case($val,CASE_LOWER);
                        $resultdata['ECS'][$val['cpu']][]=$val;
                    }
                    unset($result);
                    break;
                case 2:
                    $resultoneService['model']='cvm';
                    //$actiondata=array('Version'=>'2017-08-01','Filters.0.Name'=>'zone','Filters.0.Values.1'=>$zoneid,'Filters.1.Name'=>'instance-family','Filters.1.Values.1'=>$desciribeInstancetype[1]);
                    $actiondata=array('Version'=>'2017-08-01','Filters.0.Name'=>'zone','Filters.0.Values.1'=>$zoneid);
                    $result=$this->tencat($resultoneService,'DescribeInstanceTypeConfigs',$actiondata)['Response']['InstanceTypeConfigSet'];
                    $Memory=[1,2,4,6,8,12,16,24,32,48,56,64];
                    $result=array_filter($result,function($val) use ($Memory){
                        if($val['CPU']<=32 && in_array($val['Memory'],$Memory)){
                            return true;
                        }else{
                            return false;
                        }
                    });

                    $instancetype=array("S2"=>"标准型","I2"=>"高IO型","M2"=>"内存型","C2"=>"计算型","S1"=>"标准型","I1"=>"高IO型","M1"=>"内存型");
                    foreach ($result as $key=>$val){
                        $name=$instancetype[$val['InstanceFamily']];//array_search((string)trim($val['InstanceFamily']),$instancetype);
                        if(!empty($name)) {
                            $val['instanceTypeId']=$val['CPU'].":".$val['Memory'];
                            $val=array_change_key_case($val,CASE_LOWER );
                            $resultdata[$val['instancefamily'] . ':' . $name][$val['cpu']][] = $val;
                        }
                    }
                    unset($result);
                    break;
                case 4:
                    //获取regions下面zone和对应可开通机型
                    $actiondata=array('setRegionId'=>$resultoneService['Region']);
                    $resultzone = json_decode(json_encode($this->ali($resultoneService, '\Ecs\Request\V20140526\DescribeZonesRequest', $actiondata)->Zones->Zone),true);//获取组
                    //获取当前zone下面的机型
                    $resultzone=array_values(array_filter($resultzone,function($val) use ($zoneid,$resultdata){
                        if($val['ZoneId'] == $zoneid){
                            return true;
                        }else{
                            return false;
                        }
                    }));
                    $resultzone=$resultzone[0]['AvailableInstanceTypes']['InstanceTypes'];
                    if(!empty($resultzone)){
                        //获取当前regions下的所有机型
                        $resultali = json_decode(json_encode($this->ali($resultoneService, '\Ecs\Request\V20140526\DescribeInstanceTypesRequest', [])->InstanceTypes->InstanceType),true);
                        $Memory=[1,2,4,8,16,32,64,128,256];
                        //过滤不包含当前zone下面的机器，和cpu不大于32,内存包含规定的
                        $resultali=array_filter($resultali ,function($val) use ($resultzone,$Memory){
                            if(in_array($val['InstanceTypeId'],$resultzone) && $val['CPU']<=32 && in_array($val['MemorySize'],$Memory)){
                                return true;
                            }else{
                                return false;
                            }
                        });
                        unset($resultzone);
                        //组装返回可选的机器型号
                        $instancetype=["ecs.xn4"=>"共享基本型","ecs.n4"=>"入门级共享计算型","ecs.mn4"=>"入门级共享通用型","ecs.sn2"=>"通用型(原独享)","ecs.g5"=>"通用型","ecs.sn2ne"=>"通用网络增强型","ecs.sn1"=>"计算型(原独享)","ecs.sn1ne"=>"计算网络增强型","ecs.c5"=>"计算型"];
                        foreach ($resultali as $key=>$val){
                            $name=$instancetype[$val['InstanceTypeFamily']];
                            if(!empty($name)) {
                                $val['cpu']=$val['CpuCoreCount'];
                                $val['memory']=$val['MemorySize'];
                                $val['instancetype']=$val['InstanceTypeFamily'];
                                $val['instancetypeid']=$val['InstanceTypeId'];
                                $resultdata[$val['InstanceTypeFamily'].":".$name][$val['cpu']][] = $val;
                            }
                        }
                        unset($resultali,$instancetype);
                    }
                default:
                    break;
            }
            if(empty($resultdata)){
                $this->ajaxError("服务商数据错误，请联系平台管理员");
            }
            ksort($resultdata);
            /* $imgsql="select img_name as name,img_id as id from f_img WHERE img_type  = " . $siteid." ";
             $resultimg=$Model->query($imgsql);*/
            $this->ajaxSuccess("",array('host'=>$resultdata,'hostimg'=>[],'Memory'=>$Memory));
            exit;
        }
    }


    /**
     *@auth:leishaofa
     *@date:2017804
     * @efect:新增平台套餐
     */
    public function platfromPakeageaddto(){
        if(IS_AJAX){
            $id=is_numeric($_GET['keyid'])>0?$_GET['keyid']:'';
            //表自增id
            $siteModel = M('package_price','f_',C('flashSale'));
            if(IS_POST) {
                 if (!$siteModel->autoCheckToken($_POST)){
                     parent::ajaxError('表单已提交过！请关闭重新填写！'); // 令牌验证错误
                 }
                $data = $_POST;
                unset($data['__hash__']);
                if(!empty($_GET['keyid']) && empty($id)){//传了id但是id不是数字
                    $this->ajaxError("修改失败");
                }
                if(!empty($id)){
                    //修改
                    $status=filter_var($_POST['status'],FILTER_VALIDATE_BOOLEAN)?1:2;
                    //$sql="INSERT INTO f_package_price(id,price,status,package_remark) VALUES (".$id.",".$data['taocanprice'].",".$status.",'".json_encode($resultdata['package_remark'])."')ON DUPLICATE KEY UPDATE price=VALUES(price),status=VALUES(status),package_remark=VALUES(package_remark)";
                    $sql="INSERT INTO f_package_price(id,status) VALUES (".$id.",".$status.")ON DUPLICATE KEY UPDATE status=VALUES(status)";

                    $resultsql=$siteModel->execute($sql);
                    $msg=$resultsql>0?"修改成功":"修改失败";
                }else {
                    $server=C('ServerProvider')[$data['serverid']];
                    if (empty($server) || !$server['is_display']) {
                        $this->ajaxError("主机商错误");
                    }
                    if (empty($data['hostsdk'])) {
                        $this->ajaxError("请选择cpu和内存");
                    }
                    $desciribeInstancetype=explode(':',htmlspecialchars($data['describeTypes']));
                    $data['zone']=$desciribeInstancetype[0];
                    $issetsql="select id from f_package_price where ser_type=".$server['val']."  and package_remark like '%hostsdk\":\"".$data['hostsdk']."\"%' and package_remark like '%zone\":\"".$data['zone']."\"}'  limit 1" ;
                    $insetresult= $siteModel->query($issetsql);
                    if(empty($insetresult)) {
                        $sql = "insert IGNORE into f_package_price(ser_type,ser_name,package_remark) values(" . $server['val'] . ",'" . C('ServerName')[$data['serverid']] . "','" . json_encode($data) . "')";
                        $resultsql = $siteModel->execute($sql);
                        $msg = $resultsql > 0 ? "添加成功" : "添加失败";
                    }else{
                        $resultsql=0;
                        $msg="该配置已经添加";
                    }
                }
                if ($resultsql > 0) {
                    parent::ajaxSuccess($msg);
                } else {
                    parent::ajaxError($msg);
                }
            }
            //查询修改信息
            if(!empty($id) && empty($_POST)){
                $sql="select * from f_package_price where id=".$id." ";
                $resultdata=$siteModel->query($sql);
                $resultdata[0]['package_remark']=json_decode( $resultdata[0]['package_remark'],true);
                if($resultdata){
                    $resultdata[0]['sercity']=getservercity($resultdata[0]['package_remark']['zone'],$resultdata[0]['ser_type']);
                    $this->assign('date',$resultdata[0]);
                }
            }
            $this->display('platfromPakeageupdate');
        }
    }


    /**
     *@auth:leishaofa
     *@date:20417802
     * @efect:平台套餐
     */
    public function platfromPakeage(){
        $siteModel = M('package_price','f_',C('flashSale'));
        $number=10;
        $where[]=is_numeric($_GET['siteid'])?" ser_type = '".$_GET['siteid']."'":"";
        $where[]=is_numeric($_GET['pagestatus']) && $_GET['pagestatus']>0?"status = '".$_GET['pagestatus']."'":'';
        $where=array_filter($where);
        $where=empty($where)?'':' where '.implode(' and ',$where);
        if(IS_AJAX){
            $currPage=is_numeric($_GET['p'])?$_GET['p']:1;
            if($currPage>0){
                $sql="select a.id as keyid,a.ser_type as sertype,a.package_remark as url,a.ser_name as sername,a.status as isstatus from f_package_price as a ".$where." order by a.id desc limit ".($currPage-1)*$number.",".$number." ";
                $listdata=$siteModel->query($sql);
                $listdata=array_map(function($val){
                    $val['url']=json_decode($val['url'],true);
                    return $val;
                },$listdata);
                $this->ajaxSuccess("成功",$listdata);
            }else{
                $this->ajaxError("没有数据",[]);
            }
            exit;
        }
        $sql="select count(1) as countnum from f_package_price".$where;
        $resultsql=$siteModel->query($sql);
        $this->assign('page',ceil($resultsql[0]['countnum']/$number));
        $this->display();
    }


}